<template>
  <div class="user-management-container">
    <!-- 统一标题样式 -->
    <div class="header-section">
    <h2>用户列表</h2>
      <div class="title-line"></div>
    </div>
    <!-- 搜索与筛选区域 -->
<el-card class="filter-card">
  <div class="filter-content">
    <el-input 
      v-model="queryStr" 
      placeholder="请输入用户名或ID" 
      clearable
      @clear="queryInfo"
      style="width: 300px">
      <template #prepend>
        <el-icon><Search /></el-icon>
      </template>
    </el-input>
    
    <div class="filter-actions">
      <el-button 
        class="custom-primary-button"
        type="primary" 
        @click="queryInfo">
        查询用户
      </el-button>
      <el-button 
        class="custom-reset-button"
        @click="resetFilters">
        重置筛选
      </el-button>
    </div>
  </div>
</el-card>

    <!-- 用户列表卡片 -->
    <el-card class="user-list-card">
      <div class="list-header">
        <div class="header-gradient"></div>
        <h3>用户列表</h3>
        <div class="total-users">
          共 <span class="highlight">{{ pageInfo.total || 0 }}</span> 位用户
        </div>
      </div>
      
      <el-table :data="tableData" stripe style="width: 100%" class="user-table">
        <el-table-column prop="username" label="用户名" width="140" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag 
              :type="scope.row.status === 1 ? 'success' : 'danger'" 
              effect="dark"
              round>
              {{ scope.row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="200" />
        <el-table-column prop="role" label="角色" width="120">
          <template #default="scope">
            {{ formatRole(scope.row.role) }}
          </template>
        </el-table-column>
       <el-table-column prop="createTime" label="注册时间" width="180">
      <template #default="scope">
        {{ formatDate(scope.row.createTime) }}
      </template>
    </el-table-column>
        <el-table-column prop="right" label="操作" min-width="160">
          <template #default="scope">
            <div class="action-buttons">
              <el-button 
                class="detail-button"
                link 
                type="primary" 
                size="small" 
                @click="openDetailDialog(scope.row.userId)">
                <el-icon><View /></el-icon> 详情
              </el-button>
              <el-button 
                class="status-button"
                link 
                type="primary" 
                size="small" 
                @click="openStatusDialog(scope.row)">
                <el-icon><Edit /></el-icon> 状态
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页控件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageInfo.total || 0"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 详情对话框 - 样式优化 -->
    <el-dialog 
      v-model="dialogDetailVisible" 
      title="用户详细信息" 
      width="500"
      class="user-detail-dialog">
      <div class="detail-item">
      <span class="detail-label">注册时间：</span>
      <span class="detail-value">{{ formatDate(form.createTime) }}</span>
    </div>
      <div class="user-detail-card">
        <div class="user-avatar">
          <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 15px;">
            <div class="user-name">{{ form.username }}</div>
            <el-tag 
              :type="form.status === 1 ? 'success' : 'danger'" 
              effect="dark"
              class="status-tag">
              {{ form.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </div>
        </div>
        
        <el-divider />
        
        <div class="detail-grid">
          <div class="detail-item">
            <span class="detail-label">邮箱：</span>
            <span class="detail-value">{{ form.email || '-' }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">手机号：</span>
            <span class="detail-value">{{ form.phone || '-' }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">角色：</span>
            <span class="detail-value">{{ formatRole(form.role) }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">姓名：</span>
            <span class="detail-value">{{ form.realName || '-' }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">性别：</span>
            <span class="detail-value">{{ formatGender(form.gender) }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">学校：</span>
            <span class="detail-value">{{ form.school || '-' }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">目标院校：</span>
            <span class="detail-value">{{ form.targetSchool || '-' }}</span>
          </div>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogDetailVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 状态修改对话框 - 样式优化 -->
    <el-dialog 
      v-model="dialogStatusVisible" 
      title="修改用户状态" 
      width="400"
      class="status-dialog">
      <div class="status-form">
        <div class="current-status">
          <span>用户名：</span>
          <strong>{{ form.username }}</strong>
        </div>
        
        <div class="current-status">
          <span>当前状态：</span>
          <el-tag :type="form.status === 1 ? 'success' : 'danger'" effect="dark">
            {{ form.status === 1 ? '正常' : '禁用' }}
          </el-tag>
        </div>
        
        <div class="status-selection">
          <span>新状态：</span>
          <el-select v-model="newStatus" placeholder="请选择状态">
            <el-option label="正常" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogStatusVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            class="confirm-button"
            @click="updateUserStatus">
            确认修改
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { Search, View, Edit } from '@element-plus/icons-vue'

export default {
  components: {
    Search,
    View,
    Edit
  },
  data() {
    return {
      dialogDetailVisible: false,
      dialogStatusVisible: false,
      queryStr: "",
      form: {},
      newStatus: null,
      tableData: [],
      pageInfo: {},
      pageSize: 10,
      currentPage: 1,
      avatarUrl: "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"
    }
  },
  mounted() {
    this.getUserPages(1, this.pageSize)
  },
  methods: {
    
    // 优化日期格式化方法
    formatDate(dateString) {
      if (!dateString) return '-';
      try {
        const date = new Date(dateString);
        // 格式化为本地时间：YYYY-MM-DD HH:mm:ss
        return date.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit',
          hour12: false
        }).replace(/\//g, '-');
      } catch (e) {
        console.error('日期格式化错误:', e);
        return dateString; // 返回原始字符串作为回退
      }
    },

    formatGender(gender) {
      if (gender === 'male') return '男';
      if (gender === 'female') return '女';
      if (gender === 'other') return '保密';
      return gender || '-';
    },
    formatRole(role) {
      if (role === 'student') return '学生';
      if (role === 'admin') return '管理员';
      return role || '-';
    },
    formatDate(dateString) {
      if (!dateString) return '';
      try {
        const date = new Date(dateString);
        return date.toLocaleString();
      } catch (e) {
        return dateString;
      }
    },
    getUserPages(pageNum, pageSize) {
      axios.get("/api/user/pages", {
        params: {
          pageNum: pageNum,
          pageSize: pageSize,
          keyword: this.queryStr
        }
      }).then(response => {
        this.pageInfo = response.data;
        this.tableData = response.data.list;
      }).catch(error => {
        console.error("获取用户数据失败:", error)
        ElMessage.error("获取用户数据失败: " + (error.response?.data?.message || error.message))
      })
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.getUserPages(this.currentPage, pageSize)
    },
    handleCurrentChange(pageNum) {
      this.currentPage = pageNum
      this.getUserPages(pageNum, this.pageSize)
    },
    queryInfo() {
      this.currentPage = 1
      this.getUserPages(1, this.pageSize)
    },
    resetFilters() {
      this.queryStr = "";
      this.currentPage = 1;
      this.getUserPages(1, this.pageSize);
    },
    openDetailDialog(userId) {
      axios.get("/api/user/find", {
        params: { id: userId }
      })
      .then(response => {
        this.form = response.data.data || response.data;
        this.dialogDetailVisible = true;
      })
      .catch(error => {
        let errorMessage = "获取用户详情失败";
        if (error.response) {
          errorMessage += `: ${error.response.status}`;
          if (error.response.data?.message) {
            errorMessage += ` - ${error.response.data.message}`;
          }
        }
        ElMessage.error(errorMessage);
      })
    },
    openStatusDialog(row) {
      this.form = { ...row };
      this.newStatus = row.status;
      this.dialogStatusVisible = true;
    },
    updateUserStatus() {
      if (this.form.status === this.newStatus) {
        ElMessage.warning("状态未改变")
        this.dialogStatusVisible = false
        return
      }

      axios.put("/user/status", null, {
        params: {
          userId: this.form.userId,
          status: this.newStatus
        }
      })
      .then(response => {
        if (response.data === 1 || response.data === true) {
          ElMessage.success("状态更新成功")
          const user = this.tableData.find(u => u.userId === this.form.userId)
          if (user) user.status = this.newStatus
          this.form.status = this.newStatus;
        } else {
          ElMessage.error("状态更新失败: " + (response.data?.message || "未知错误"))
        }
        this.dialogStatusVisible = false
      })
      .catch(error => {
        console.error("状态更新失败:", error)
        ElMessage.error("状态更新失败: " + (error.response?.data?.message || error.message))
      })
    }
  }
}
</script>

<style scoped>

/* 在style部分添加下划线样式 */
.title-line {
  width: 50px;
  height: 4px;
  background: linear-gradient(90deg, #3b527a, #4e6694);
  border-radius: 2px;
}
/* 整体布局和背景 */
.user-management-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 标题区域 */
.header-section {
  margin-bottom: 5px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e6e9ed;
}

.header-section h2 {
  color: #1a2f54;
  font-weight: 600;
  font-size: 22px;
  margin-bottom: 8px;
}

.subtitle {
  color: #606266;
  font-size: 14px;
  margin-top: 0;
}

/* 卡片通用样式 */
.filter-card, .user-list-card {
  border-radius: 10px;
  margin-bottom: 24px;
  border: none;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

/* 卡片头部样式 */
.filter-header, .list-header {
  position: relative;
  padding: 16px 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.filter-header h3, .list-header h3 {
  color: white;
  position: relative;
  z-index: 2;
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.header-gradient {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 100%;
  background: linear-gradient(135deg, #4e6694 0%, #3b527a 100%);
  z-index: 1;
}
/* filter-content的样式 */
.filter-content {
  padding: 15px 20px; /* 调整上下padding为15px，左右20px */
  display: flex;
  align-items: center;
  gap: 15px;
}

/* 需要进一步微调，可以添加 */
.filter-card {
  padding: 0; /* 确保卡片内部没有额外padding */
}

.filter-actions {
  display: flex;
  gap: 10px;
}

/* 按钮样式 */
.custom-primary-button {
  background: linear-gradient(135deg, #4e6694 0%, #3b527a 100%);
  border: none;
  color: white;
  transition: all 0.3s;
  box-shadow: 0 2px 6px rgba(26, 47, 84, 0.3);
}

.custom-primary-button:hover {
  background: linear-gradient(135deg, #3b527a 0%, #4e6694 100%);
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(26, 47, 84, 0.4);
}

.custom-reset-button {
  background: #f0f2f5;
  border-color: #dcdfe6;
  color: #606266;
  transition: all 0.3s;
}

.custom-reset-button:hover {
  background: #e4e7ed;
  color: #1a2f54;
}

/* 用户列表样式 */
.user-list-card {
  position: relative;
}

.total-users {
  position: relative;
  z-index: 2;
  color: white;
  font-size: 14px;
}

.total-users .highlight {
  font-weight: bold;
  color: #ffd04b;
}

.user-table {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.user-table .el-table__header) {
  background-color: #f0f5ff;
}

:deep(.user-table .el-table th) {
  background-color: #f0f5ff;
  color: #1a2f54;
  font-weight: 600;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.detail-button, .status-button {
  padding: 5px 10px;
  border-radius: 4px;
  transition: all 0.2s;
}

.detail-button {
  background-color: rgba(64, 158, 255, 0.1);
  color: #409eff;
}

.status-button {
  background-color: rgba(103, 194, 58, 0.1);
  color: #67c23a;
}

.detail-button:hover {
  background-color: rgba(64, 158, 255, 0.2);
}

.status-button:hover {
  background-color: rgba(103, 194, 58, 0.2);
}

/* 分页样式 */
.pagination-container {
  padding: 20px;
  display: flex;
  justify-content: center;
}

/* 对话框样式 */
.user-detail-dialog .user-detail-card {
  padding: 20px;
  background: #f9fafc;
  border-radius: 8px;
}

.user-avatar {
  text-align: center;
  margin-bottom: 0;
}

.user-name {
  font-size: 18px;
  font-weight: 600;
  color: #1a2f54;
}

.status-tag {
  font-size: 12px;
  padding: 4px 12px;
}

.detail-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px;
}

.detail-item {
  display: flex;
  align-items: center;
}

.detail-label {
  font-weight: 600;
  color: #606266;
  min-width: 80px;
}

.detail-value {
  color: #1a2f54;
}

.status-dialog .status-form {
  padding: 10px 20px;
}

.current-status, .status-selection {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  font-size: 15px;
}

.current-status span, .status-selection span {
  width: 80px;
  color: #606266;
}

.confirm-button {
  background: linear-gradient(135deg, #4e6694 0%, #3b527a 100%);
  border: none;
}

/* 响应式调整 */
@media (max-width: 992px) {
  .filter-content {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .detail-grid {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .action-buttons {
    flex-direction: column;
  }
}
</style>